package com.miya.demo.handler.process;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.miya.demo.common.enums.ProcessNameEnum;
import com.miya.demo.handler.process.processor.Processor;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;

/**
 * @author CaiXiaowei
 * @description 流程引擎抽象类
 * @date 2024/6/27 11:21
 */
@Slf4j
public abstract class AbstractProcessEngineImpl implements ProcessEngine {

    @Override
    public void start(ProcessRequest request, ProcessContext context) {
        // 打印流程引擎开始日志
        log.info("processEngine start, request:{}", JSONUtil.toJsonStr(request));

        // 获取流程引擎执行器
        List<ProcessNameEnum> processors = getProcessors();

        try {
            // 逐个运行执行器
            processors.forEach(processName -> {
                Object bean = SpringUtil.getBean(processName.getCode());
                if (!(bean instanceof Processor)) {
                    log.error("processor: {} not exist or type is incorrect", processName);
                    return;
                }
                // 执行器开始日志
                log.info("processor {} start", processName);
                Processor processor = (Processor) bean;
                if (!processor.needExecute(request, context)) {
                    log.info("processor {} skipped", processName);
                    return;
                }
                // 执行器执行
                processor.execute(request, context);
                // 执行器结束日志
                log.info("processor {} end", processName);
            });
        } catch (Exception e) {
            log.error("processEngine execute error {}", Arrays.toString(e.getStackTrace()));
            throw e;
        }
        // 打印执行器执行完成日志
        log.info("processEngine end:{}", JSONUtil.toJsonStr(context));
    }

    protected abstract List<ProcessNameEnum> getProcessors();
}
